package com.cennavi.minemapdemo.activity.overlayer;

import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.widget.SeekBar;

import com.cennavi.minemapdemo.R;
import com.cennavi.minemapdemo.bean.DataBean;
import com.cennavi.minemapdemo.util.Config;
import com.google.gson.Gson;
import com.minedata.minemap.MinemapAccountManager;
import com.minedata.minemap.camera.CameraPosition;
import com.minedata.minemap.geometry.LatLng;
import com.minedata.minemap.map.MapView;
import com.minedata.minemap.map.MineMap;
import com.minedata.minemap.overlay.FillLayer;
import com.minedata.minemap.overlay.FillLayerOptions;
import com.minedata.minemap.overlay.FillLayerOptions.FillItem;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

public class FillActivity extends AppCompatActivity {

    private MapView mapView;
    private static MineMap mineMap = null;
    private FillLayer mLayer;
    private SeekBar mSeekBar;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        MinemapAccountManager.getInstance(getApplicationContext(),
                "57d9ee4eec2d4b1f87f8efa7eba2178e",
                null,
                "5699");

        setContentView(R.layout.activity_item);
        mapView = (MapView) findViewById(R.id.mapView);
        mSeekBar = (SeekBar) findViewById(R.id.seekbar);
        mSeekBar.setOnSeekBarChangeListener(seekBarListener);

        //mine map sdk 2.0.6之前生效
        // mapView.setStyleUrl("http://minedata.cn/service/solu/style/id/5699");

        mapView.addMapRenderCallback(new MapView.OnMapReadyListener() {
            @Override
            public void onMapReady(MineMap mineMap) {
                FillActivity.mineMap = mineMap;

                mineMap.getUiSettings().setCompassEnabled(true);
                mineMap.getUiSettings().setRotateGesturesEnabled(true);
                mineMap.setStyleUrl(Config.mBaseUrl + Config.MAP_ID, new MineMap.OnStyleLoadedListener() {

                    @Override
                    public void onStyleLoaded(String s) {

                        //mine map sdk 2.0.6及之后版本这样使用
                        //layers 和 images 都在这里面加载
                        addLayersToMap();
                    }
                });
                mineMap.setCameraPosition(
                        //41.805629,123.432359   沈阳
                        //34.2419937,108.9418989 西安   108.81292 34.36734
                        //39.897424, 116.356508  北京    116.3564, 39.8974
                        //18.162968，102.591348  老挝万象附近
                        new CameraPosition.Builder().target(new LatLng(27.6292, 106.8451)).zoom(17.3)
                                .tilt(60)//设定倾斜角度
                                .bearing(0) //摄像机指向的方向,从北部顺时针方向设置
                                .zoom(9)
                                .build());
                mineMap.setMaxZoomPreference(21);//设置最高展示级别，最高为21级别
                mineMap.setMinZoomPreference(6);//设置最低的展示级别
//                mineMap.setDebugActive(true);
                mineMap.setRepaint(false);

            }

        });

    }

    private SeekBar.OnSeekBarChangeListener seekBarListener = new SeekBar.OnSeekBarChangeListener() {

        private int value = 0;

        @Override
        public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
            value = i;
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {

        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
            Message msg = new Message();
            msg.what = 0;
            msg.arg1 = value;
            mHandler.sendMessage(msg);
        }
    };

    private boolean isUpdate = false;

    private Handler mHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            final float value = (float) msg.arg1 / 100;

            switch (msg.what) {
                case 0: {
                    if (!isUpdate) {
                        isUpdate = true;
                        List<FillItem> items = mLayer.getOptions().getItems();
                        for (FillItem item : items) {
                            item.setAlpha(value);
                        }
                        mLayer.update();
                        isUpdate = false;
                    }

                    break;
                }

            }
        }
    };

    private void addLayersToMap() {

        {
            FillLayerOptions options = new FillLayerOptions("filllayer");
            options.addAll(getData(loadJsonFromAsset("shenyang.json", FillActivity.this)));
            mLayer = mineMap.addLayer(options);
        }

        List<FillLayerOptions.FillItem> items = new ArrayList<>();
        FillLayerOptions.FillItem item1 = new FillLayerOptions.FillItem();
        item1.setAlpha(0.8f);
        item1.setColor(Color.parseColor("#EE82EE"));
        item1.setOutlineColor(Color.parseColor("#FF00FF"));
        items.add(item1);

        FillLayerOptions options = new FillLayerOptions("filllayer");
        options.setUrl("http://202.98.195.207:9090/GZInterface/cnPolygonTileService/getPolygons/{z}/{x}/{y}?areacode=520000000000");
        options.setSourceLayer("admin");

        options.addAll(items);
        mineMap.addLayer(options);

    }

    public List<FillItem> getData(String data) {

        if (data.isEmpty()) {
            return null;
        }

        List<FillItem> items = new ArrayList<>();

        DataBean bean = new Gson().fromJson(data, DataBean.class);
        int size = bean.getFeatures().size();
        for (int i = 0; i < size; i++) {
            DataBean.FeaturesBean featuresBean = bean.getFeatures().get(i);

            List<List<Double>> points = featuresBean.getGeometry().getCoordinates().get(0);
            ArrayList<LatLng> polygons = new ArrayList<>();
            for (int j = 0; j < points.size(); j++) {
                polygons.add(new LatLng(points.get(j).get(1), points.get(j).get(0)));
            }

            FillItem item = new FillItem(polygons);
            if (i % 5 == 0) {
                item.setColor(Color.parseColor("#ff0000"));
                item.setOutlineColor(Color.parseColor("#ff0000"));
                item.setAlpha(0.5f);
            } else if (i % 5 == 1) {
                item.setColor(Color.parseColor("#00ff00"));
                item.setOutlineColor(Color.parseColor("#00ee00"));
            }
            items.add(item);
        }
        return items;
    }

    private String loadJsonFromAsset(String filename, Context context) {
        try {
            // loads in GeoJSON files from the assets folder.
            InputStream is = context.getAssets().open(filename);
            int size = is.available();
            byte[] buffer = new byte[size];
            is.read(buffer);
            is.close();
            return new String(buffer, "UTF-8");
        } catch (Exception e) {

        }
        return null;
    }

    //生命周期
    @Override
    protected void onStart() {
        super.onStart();
        if (mapView != null)
            mapView.onStart();
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (mapView != null)
            mapView.onStop();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (mapView != null)
            mapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (mapView != null)
            mapView.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mapView != null)
            mapView.onDestroy();
    }

    @Override
    public void onLowMemory() {
        super.onLowMemory();
        if (mapView != null) {
            mapView.onLowMemory();
        }
    }

}
